
// lib
// config
// script & methods & public
// state
import { userState } from "state/global";
// http
import { open, bag, isOkRes } from "public/http/api";
// service
import { simpleResService } from "public/service/simple.service";
import { createApiUrl, setUrlWithParams } from "public/http/core";
// api
import {
  API_CODE,
  API_LOGIN,
  API_REGISTER,
  API_UPDATE_INFO,
  API_UPDATE_PASS,
  API_UPDATE_USER_PASS,
  ReqLogin,
  ReqRegister,
  ReqUpdateInfo,
  ReqUpdatePass,
  ResLogin,
} from "./api";
import logUtils from "utils/logUtils";
import _ from "lodash";
// interface
// 其它

// 获取图形验证码
export function getCodeService() {
  const path = setUrlWithParams(createApiUrl(API_CODE), {}, true);
  logUtils.info("验证码链接", path);
  // 返回
  return path;
}
export function getCodeKey(codeUrl:String){
  if(_.isUndefined(codeUrl) || codeUrl.length < 13){
    return ""
  }
  return codeUrl.substring(codeUrl.length - 13)
}
// 注册
export async function userRegisterService(user:ReqRegister) {
  // 打开接口
  const a1 = await open<ReqRegister, ResObject<UserDto>>(API_REGISTER, user);
  // 创建返回数据
  const data = bag<boolean>(a1);
  // 成功后处理
  if (isOkRes(a1)) {
    console.log('-----',a1)
    // userState.setAccount(a1.data.user);
    // userState.setToken(a1.data.authorization);
    data.payload = true;
  }
  return data;
}
// 登录
export async function loginService(way: string, key: string, vc: string,co:string) {
  // 打开接口
  const a1 = await open<ReqLogin, ResLogin>(API_LOGIN, {
    userName: way.trim(),
    password: key.trim(),
    captcha: vc.trim(),
    validateCode:getCodeKey(co)
  });
  // 创建返回数据
  const data = bag<boolean>(a1);
  // 成功后处理
  if (isOkRes(a1)) {
    userState.setAccount(a1.data.user);
    userState.setToken(a1.data.authorization);
    data.payload = true;
  }
  return data;
}

// 退出登录
export async function logoutService() {
  // const result = await simpleResService<any>(API_LOGOUT, {});
  // if (result.payload) {
    userState.setToken("")
    userState.cleanData()
  // }
  // return result;
}
// 修改密码
export function updateUserPwdService(oldPwd: string, newPwd: string) {
  const params: ReqUpdatePass = {
    oldPwd:oldPwd.trim(),
    newPwd:newPwd.trim(),
  };
  let API = API_UPDATE_PASS
  if (userState.isUser()) {
    API = API_UPDATE_USER_PASS
  }
  const result = simpleResService<ReqUpdatePass>(API, params);
  return result;
}
// 修改信息
export function letUserInfoUpdateService(params: ReqUpdateInfo) {
  const result = simpleResService<ReqUpdateInfo>(API_UPDATE_INFO, params);
  return result;
}
